class UsersController < ApplicationController
  
  before_filter :authorize, :except => [:new, :create]
  
  def show
    @user = User.current
  end

  def edit
    @user = User.find(params[:id])
  end
  
  def new
    @user = User.new
  end

  def create    
    if params[:user][:enterprise_id].present?
      @enterprise = Enterprise.find(params[:user][:enterprise_id]) 
      @enterprise.update_attributes :name => params[:enterprise_name]
    else
      @enterprise = Enterprise.create(:name => params[:enterprise_name])
      params[:user][:enterprise_id] = @enterprise.id
    end    
    @user = User.new(params[:user])
    if @user.save 
      @enterprise.set_admin!(@user)
      session[:current_user_id] = @user.id
      redirect_to(root_url)
    else
      render(:new)
    end
  end

  def update
    @user = User.find(params[:id])
    render :edit if not @user.update_attributes(params[:user])
  end

  def edit_enterprise
    edit
  end

  def update_enterprise
    enterprise = Enterprise.find(params[:id])
    render :edit_enterprise if not enterprise.update_attributes(params[:enterprise])
  end

  def show_enterprise
    show
  end

  def edit_password
    @user = User.current
  end

  def update_password
    @user = User.find(params[:id])
    render :edit_password if not @user.update_attributes(params[:user])
  end
  
  def employees
    
  end
  
  def new_employee
    @user = User.new(:enterprise_id => User.current.enterprise_id)
  end
  
  def new_group
    @group = Group.new(:enterprise_id => User.current.enterprise_id)
  end

  def create_group
    @group = Group.new(params[:group])
    render :new_group if not @group.save
  end

  def edit_group
    @group = Group.find(params[:id])
  end

  def update_group
    @group = Group.find(params[:id])
    render :edit_group if not @group.update_attributes(params[:group])
  end

  def destroy_group
    @group = Group.find(params[:id])
    @group.destroy
  end

  def groups
    
  end

  def create_employee
    @user = User.new(params[:user])
    render :new_employee if not @user.save
  end
  
  def edit_employee
    @user = User.find(params[:id])
  end
  
  def update_employee
    @user = User.find(params[:id])
    render :edit_employee if not @user.update_attributes(params[:user])
  end
  
  def lock_employee
    @user = User.find(params[:id])
    @user.locked!
  end
  
  def active_employee
    @user = User.find(params[:id])
    @user.active!
  end
  
  def reset_employee_password
    @user = User.find(params[:id])
    @user.reset_password!
  end

  def update_feed_view_type    
    current_user.update_attributes :feed_view_type => params[:feed_view_type]
  end
  
end
